<template>
  <div>
    <div
      class="filebox ks-row-middle bgwh"
      v-for="(i, index) in fileList"
      :key="index"
    >
      <div class="g3 ks-col ell f14">{{ i.name }}</div>
      <el-button type="text" icon="el-icon-delete" @click="deleteFile(index)"
        >删除
      </el-button>
    </div>
    <el-upload
      v-show="!disabled"
      v-if="multiple || fileList.length < 1"
      :drag="drag"
      action=""
      :accept="accept"
      :show-file-list="false"
      :http-request="handleHttpRequest"
      :before-upload="beforeUpload"
    >
      <template v-if="drag">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
      <template v-else>
        <div class="uploader dib" v-if="image">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </div>
        <el-button icon="el-icon-upload2" v-else>上传</el-button>
      </template>
    </el-upload>
  </div>
</template>
<script>
export default {
  props: {
    beforeUpload: {
      type: Function,
      default: () => {
        return true
      },
    },
    disabled: { default: false, type: Boolean },
    drag: { default: false, type: Boolean },
    multiple: {
      default: false,
      type: Boolean,
    },
    value: {
      default: "",
    },
    accept: {
      default: "",
      type: String,
    },
  },
  data() {
    return {
      fileList: [],
    }
  },
  watch: {
    value: {
      handler: function (value) {
        if (value) {
          this.fileList = Array.isArray(value) ? value : [value]
        } else {
          this.fileList = []
        }
      },
      immediate: true,
    },
  },
  methods: {
    async handleHttpRequest(value) {
      let file = value.file
      this.fileList.push(file)
      if (this.fileList.length === 0) {
        this.$emit("input", "")
      } else if (this.multiple) {
        this.$emit("input", this.fileList)
      } else {
        this.$emit("input", this.fileList[0])
      }
    },
    deleteFile(index) {
      this.fileList.splice(index, 1)
      if (this.fileList.length === 0) {
        this.$emit("input", "")
      } else if (this.multiple) {
        this.$emit("input", this.fileList)
      } else {
        this.$emit("input", this.fileList[0])
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.filebox {
  width: 100%;
  height: 28px;
  border-radius: 2px;
  padding: 0 8px;
  background: #f4f9ff;
  margin-bottom: 8px;
}
</style>
